
package com.mengmeizi.net;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UploadFileUtiles {

    private static final Map<String, String> contentTypes = new HashMap<String, String>();

    static {
        initContentTypes();
    }

    private static final void initContentTypes() {
        contentTypes.put("jpeg", "image/jpeg");
        contentTypes.put("jpg", "image/jpeg");
        contentTypes.put("png", "image/png");
        contentTypes.put("xml", "text/xml");
    }

    public static final String getFileContentType(File file) {
        if (contentTypes.isEmpty()) {
            initContentTypes();
        }
        final String name = file.getName();
        int index = name.lastIndexOf(".");
        String subfix = "";
        if (index != -1) {
            subfix = name.substring(index + 1);
        }
        String type = contentTypes.get(subfix);
        return type == null ? "" : type;
    }

    public static final byte[] getBytes(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = fis.read(bytes)) != -1) {
            bos.write(bytes, 0, length);
        }
        return bos.toByteArray();
    }
}
